/**
 * 打印
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Spin, message } from 'antd';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import router from 'umi/router';
import printJS from 'print-js';

import {
  getUnderchargePrint,
  printAll,
  getPkgAccidentDetail,
  batchUpdateImg,
  arrivalDamagedPrintAccident,
  lossInternalItemsPrintAccident,
  lossInternalItemsPrintAll,
  arrivalDamagedPrintAll,
  overchargePrintClaim,
  downLoadCommunicate
} from './service.js';
import {
  Const
} from '../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import PicUpload from '../lessBaggageManagement/components/PicUpload';
import ShowPic from '../lessBaggageManagement/components/ShowPic';
import CompensationList from '../lessBaggageManagement/components/CompensationList'; // 赔偿单列表

class PrivateData {
  static buttonArr = [
    { text: '打印', value: '1', authCode: ['basicPermissions'] },
    { text: '修改', value: '2', authCode: ['changeIncident', 'changeAllIncident'] },
    { text: '临时赔偿', value: '3', authCode: ['changeLinShiCompensation'] },
    { text: '结案赔偿', value: '4', authCode: ['changeJieAnCompensation'] },
    { text: '图片管理', value: '5', authCode: ['basicPermissions'] },
    { text: '打印赔偿单', value: '6', authCode: ['basicPermissions'] },
  ];
}

const PrintPage = props => {

  const { location: { state } } = props;

  const [imgUrl, setImgUrl] = useState('');
  const [imgUrlArr, setImgUrlArr] = useState([]);

  const [compensationListVisible, setCompensationListVisible] = useState(false); // 赔偿单列表弹窗

  const [detailInfo, setDetailInfo] = useState({}); // 详情

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([]);

  // 获取打印数据 - 进港少收
  const { run: runGetUnderchargePrint, loading: shaoShouLoading } = useRequest(params => getUnderchargePrint(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取打印数据');
      setImgUrl(res || '');
      setImgUrlArr([]);
    }
  });
  // 获取打印数据 - 进港破损
  const { run: runArrivalDamagedPrintAccident, loading: poSunLoading } = useRequest(params => arrivalDamagedPrintAccident(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取打印数据');
      setImgUrl(res || '');
      setImgUrlArr([]);
    }
  });

  // 获取打印数据 - 内物缺失
  const { run: runLossInternalItemsPrintAccident, loading: diuShiLoading } = useRequest(params => lossInternalItemsPrintAccident(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取打印数据');
      setImgUrl(res || '');
      setImgUrlArr([]);
    }
  });

  // 获取打印数据 - 多收
  const { run: runOverchargePrintClaim, loading: duoShouLoading } = useRequest(params => overchargePrintClaim(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取打印数据');
      setImgUrl(res || '');
      setImgUrlArr([]);
    }
  });

  // 获取归档打印数据 - 少收
  const { run: runPrintAll, loading: shaoShouGDLoading } = useRequest(params => printAll(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取归档打印数据');
      let arr = res || [];
      setImgUrl('');
      setImgUrlArr(arr);
    }
  });

  // 获取归档打印数据 - 内物缺失
  const { run: runLossInternalItemsPrintAll, loading: queShiGDLoading } = useRequest(params => lossInternalItemsPrintAll(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取归档打印数据');
      let arr = res || [];
      setImgUrl('');
      setImgUrlArr(arr);
    }
  });

  // 获取归档打印数据 - 进港破损
  const { run: runArrivalDamagedPrintAll, loading: poSunGDLoading } = useRequest(params => arrivalDamagedPrintAll(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取归档打印数据');
      let arr = res || [];
      setImgUrl('');
      setImgUrlArr(arr);
    }
  });

  // 沟通记录打印
  const { run: runDownLoadCommunicate, loading: gouTongLoading } = useRequest(params => downLoadCommunicate(params), {
    manual: true,
    onSuccess (res) {
      // console.log(res, '获取沟通记录打印');
      setImgUrl(res || '');
      setImgUrlArr([]);
    }
  });

  // 事故单详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '事故单详情');
      let data = res || {};
      setDetailInfo(data.pkgAccidentDetailInfoVo || {});
      let imgArr = data.pkgImgList || [];
      handleOriginPicArr(imgArr);
      let goodFileListData = imgArr.filter(item => {
        return item.oneType === 1
      });

      let touristFileListData = imgArr.filter(item => {
        return item.oneType === 2
      });

      let paperFileListData = imgArr.filter(item => {
        return item.oneType === 3
      });

      let luggageFileListData = imgArr.filter(item => {
        return item.oneType === 4
      });

      handleLostItemPicture({
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData,
      });
    }
  });

  useEffect(() => {
    let accidentId = state.accidentId || '';
    let type = state.type || '';
    let ownerType = state.ownerType;
    getDetail();
    if (type === '6') {
      if (ownerType === 1 || ownerType === 7) {
        runArrivalDamagedPrintAccident({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        })
      }
      if (ownerType === 2) {
        runGetUnderchargePrint({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        });
      }
      if (ownerType === 3) {
        runOverchargePrintClaim({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        })
      }
      if (ownerType === 6) {
        runLossInternalItemsPrintAccident({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        })
      }
      if (ownerType === 99) {
        runDownLoadCommunicate({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        })
      }
    }
    if (type === '7') {
      if (ownerType === 1 || ownerType === 7) {
        runArrivalDamagedPrintAll({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        });
      }
      if (ownerType === 2) {
        runPrintAll({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        });
      }
      if (ownerType === 3) {}
      if (ownerType === 6) {
        runLossInternalItemsPrintAll({
          accidentId,
          imgWidthPx: 0,
          imgHeightPx: 0
        });
      }
    }
  }, [state]);

  // 获取详情
  const getDetail = useCallback(() => {
    runGetPkgAccidentDetail({
      accidentId: state.accidentId || ''
    })
  }, [state]);

  // 批量修改图片
  const { run: runBatchUpdateImg } = useRequest(data => batchUpdateImg(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '批量修改图片');
      getDetail();
      handleLostItemPicManageVisible(false);
      handleLostItemPicVisible(false);
    }
  })

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = detailInfo.accidentId
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr]);
  }

  // 打印
  const printIt = useCallback(obj => {
    printJS(obj);
  }, []);

  // 赔偿单列表 - 打开
  const compensationListOpen = useCallback((record) => {
    setCompensationListVisible(true);
  }, []);
  // 赔偿单列表 - 取消
  const compensationListCancel = useCallback(() => {
    setCompensationListVisible(false);
  }, []);
  // 赔偿单列表 - 提交
  const compensationListSubmit = useCallback(() => {
    setCompensationListVisible(false);
  }, []);

  const buttonArrClick = useCallback(val => {
    if (val === '1') {
      printIt({
        printable: 'printPageImgBox',
        type: 'html',
        maxWidth: '1920',
        scanStyles: false,
        style: '#printPageImgBox{width: 100%; height: auto; overflow: hidden;}.imgPrint{width: 100%; height: auto; display: inline-block;}',
        // targetStyles: ['*'],
        onPrintDialogClose: (val) => {
          console.log(val, 'onPrintDialogClose')
        }
      });
    }
    if (val === '2') {
      if (detailInfo.status === '2') {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
          state: {
            type: 'edit',
            ownerType: state.ownerType,
            isHave: false,
            accidentId: state.accidentId
          }
        });
      } else {
        message.warning('待处理的事故单才能进行修改');
      }
    }
    if (val === '3') {
      if (detailInfo.tempPayment === '否' && (detailInfo.status === '2' || detailInfo.status === '0')) {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditCompensation',
          state: {
            status: 'add',
            type: 0,
            itemData: detailInfo,
            detailData: {},
            ownerType: state.ownerType
          }
        });
      } else {
        message.warning('该事故单状态不能发起临时赔偿');
      }
    }
    if (val === '4') {
      if (detailInfo.closePayment === '否' && (detailInfo.status === '2' || detailInfo.status === '0')) {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditCompensation',
          state: {
            status: 'add',
            type: 1,
            itemData: detailInfo,
            detailData: {},
            ownerType: state.ownerType
          }
        });
      } else {
        message.warning('该事故单状态不能发起结案赔偿');
      }
    }
    if (val === '5') {
      handleLostItemPicManageVisible(true);
    }
    if (val === '6') {
      compensationListOpen();
    }
  }, [state, detailInfo]);

  return (
    <div className={styles.printPageContent}>
      <div className={styles.topTitle}>
        <div className={styles.topTitleLeft}>打印</div>
        <div className={styles.topTitleRight}>
          {PrivateData.buttonArr.map((item, index)=> {
            let ownerType = +state.ownerType;
            let isShow = ownerType === 99;
            for (let authItem of item.authCode) {
              if (AuthComponent.getAuth(Const.permissionsType.get(ownerType) + '.' + authItem)) {
                isShow = true;
                break;
              }
            }
            if (item.value === '1' && isShow) {
              return <Button
                type="primary"
                key={index}
                onClick={() => buttonArrClick(item.value)}
                size="small">
                {item.text}
              </Button>
            }
            if (item.value === '2' && isShow) {
              if (detailInfo.status === '2') {
                return <Button
                  type="primary"
                  key={index}
                  onClick={() => buttonArrClick(item.value)}
                  size="small">
                  {item.text}
                </Button>
              }
            }
            if (item.value === '3' && isShow) {
              if (detailInfo.tempPayment === '否' && (detailInfo.status === '2' || detailInfo.status === '0')) {
                if (ownerType === 2 || ownerType === 6) {
                  return <Button
                    type="primary"
                    key={index}
                    onClick={() => buttonArrClick(item.value)}
                    size="small">
                    {item.text}
                  </Button>
                }
              }
            }
            if (item.value === '4' && isShow) {
              if (detailInfo.closePayment === '否' && (detailInfo.status === '2' || detailInfo.status === '0')) {
                if (ownerType === 1 || ownerType === 2 || ownerType === 6 || ownerType === 7) {
                  return <Button
                    type="primary"
                    key={index}
                    onClick={() => buttonArrClick(item.value)}
                    size="small">
                    {item.text}
                  </Button>
                }
              }
            }
            if (item.value === '5' && isShow) {
              if (ownerType === 1 || ownerType === 2 || ownerType === 6 || ownerType === 7) {
                return <Button
                  type="primary"
                  key={index}
                  onClick={() => buttonArrClick(item.value)}
                  size="small">
                  {item.text}
                </Button>
              }
            }
            if (item.value === '6' && isShow) {
              if (ownerType !== 3 && ownerType !== 99) {
                return <Button
                  type="primary"
                  key={index}
                  onClick={() => buttonArrClick(item.value)}
                  size="small">
                  {item.text}
                </Button>
              }
            }
          })}
        </div>
      </div>
      {(shaoShouLoading || poSunLoading || diuShiLoading || shaoShouGDLoading || queShiGDLoading || poSunGDLoading || gouTongLoading) ? <div className={styles['f-c-c']}>
        <Spin />
      </div> : <div id="printPageImgBox" className={styles.imgContent}>
        {imgUrl && <img className="imgPrint" src={`data:image/jpeg;base64,${imgUrl}`} />}
        {imgUrlArr.map((item, index) => (
          <img key={index} className="imgPrint" src={`data:image/jpeg;base64,${item}`} />
        ))}
      </div>}
      <CompensationList
        modalVisible={compensationListVisible}
        onCancel={compensationListCancel}
        onSubmit={compensationListSubmit}
        itemData={state}
        isOnlyPrint={true}
        ownerType={state.ownerType}
      ></CompensationList>
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={state.ownerType}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          const success = await handleDelImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={state.ownerType}
        status={detailInfo.status}
      ></ShowPic>}
    </div>
  )
};

export default PrintPage;
